<script setup lang="ts">
import { watchEffect,toRaw,ref} from 'vue'
import { MoreHorizontalIcon } from 'lucide-vue-next'
import { Handle, Position, useNode, useVueFlow } from '@vue-flow/core'
import { Menubar, MenubarMenu, MenubarTrigger, MenubarContent, MenubarItem } from '@/components/ui/menubar'

import CommonInputModule from '../common-input-module.vue'
import StaticOutputModule from '../static-output-module.vue'

import { LLMNodeData, LLMNodeEvents } from './index'
import { Input } from '@/components/ui/input'
import type { NodeProps } from '@vue-flow/core'
import storeMap from '@/pina/index';
import {typesOptions} from '@/lib/dict'
defineProps<NodeProps<LLMNodeData, LLMNodeEvents>>()

const node = useNode()
const { removeNodes, addNodes, nodes } = useVueFlow()
const usePluginStore = storeMap.usePluginStore()
const template = usePluginStore.nodes.find((item:any)=>item.id==node.id)
const data = {...template?.data};
const {title} = data;
// node.id = 'Plugin_'+(nodes.value.length).toString()
// onMounted(() => {
//   node.node.data = {
//     ...node.node.data,
//     ...template
//   }
// })

function transformData(node: any): any {
  const children = node.subParams?'subParams':'children'
  const name = node.name?'name':'label'
  const transformedNode: any = {
    label: node[name],  // 替换 name 为 label
    ...(node.type ?{type: typesOptions.find(el=>el.value == (node.type+''))?.label}:{}),
    children: node[children]?.map(transformData),  // 递归转换 subParams 为 children
  };
  return transformedNode;
}

function parseIfJson(str:string){
  // 检查是否为字符串
  if (typeof str === 'string') {
    try {
      // 尝试解析为 JSON
      const parsed = JSON.parse(str);
      
      // 如果解析成功并且是对象，返回解析后的对象
      if (typeof parsed === 'object' && parsed !== null) {
        return parsed;
      }
    } catch (error) {
      // 如果解析失败，说明它只是一个普通字符串
      return str;
    }
  }
  
  // 如果已经是对象或者非字符串类型，直接返回
  return str;
}
//暂时只有一个输出template.data.output[0].value
const outputDataDisplay = template.data?parseIfJson(template.data.output[0].value)?.map((item:any)=>{
  return transformData(item)
}):[];

function handleClickDeleteBtn() {
  removeNodes(node.id)
}

function handleClickDuplicateBtn() {
  const { type, position, label, data } = node.node
 
  const newNode = {
    id: 'Plugin_'+(nodes.value.length + 1).toString(),
    type,
    position: {
      x: position.x + 100,
      y: position.y + 100
    },
    label,
    data
  }
  addNodes(newNode)
}


watchEffect(() => {
  if (node.connectedEdges && node.connectedEdges.value.length > 0) {
    if(node.node.data){
      node.node.data = {
      //给node节点添加到json当中
        id:  template.id,
        type: template.type,
        ...template.data,
        output:[
          { 
            name:'output',
            type:'5',
            value:typeof outputDataDisplay=='string'?outputDataDisplay:JSON.stringify(outputDataDisplay) 
          }
        ]
      }
    }
    // const {data} = template;
    // const SelectOption = {
    //   groupName:data.title,
    //   Options:outputData
    // }
    // storeMap.useOptionsStore().addReferenceOption(SelectOption)
  }
  // else{
  //   storeMap.useOptionsStore().clearSelectOption('插件')
  // }
})
const isEditTitle = ref(false)
const handleEdietTitle =()=>{
  isEditTitle.value = false;
  storeMap.useOptionsStore().changeTitle = data.title
}
</script>

<template>
  <div class="min-w-[450px] rounded-sm border border-gray-200 bg-white p-3 shadow-md">
    <Handle type="target" :position="Position.Left" />
    <div class="flex flex-col gap-y-4">
      <div class="flex justify-between">
        <div class="flex gap-x-2">
          <img src="~@/assets/images/icon_Api.png" class="mt-1 h-4 w-4" alt="Api icon" />
          <div class="flex flex-col gap-y-1">
            <!-- <h3 class="text-base">
              {{title}}
            </h3> -->
            <Input v-model="template.data.title" class="h-5" v-if="isEditTitle" @blur="handleEdietTitle" />
            <h3 class="text-base" v-else>{{ template.data.title }}</h3>
          </div>
        </div>

        <Menubar class="border-none">
          <menubar-menu>
            <menubar-trigger>
              <more-horizontal-icon />
            </menubar-trigger>
            <menubar-content>
              <menubar-item @click="handleClickDuplicateBtn"> 复制 </menubar-item>
              <menubar-item @click="handleClickDeleteBtn"> 删除 </menubar-item>
              <menubar-item @click="isEditTitle = true"> 重命名 </menubar-item>
            </menubar-content>
          </menubar-menu>
        </Menubar>
      </div>

      <span class="text-sm text-gray-500"
        >{{data?.props?.description}}</span
      >
      <div class="grid gap-y-3">
        <common-input-module :data="data.input" storeId="usePluginStore" :staticNameKey="[]"nodeId="node.id" />
        <static-output-module
          tip="这里是API的返回值。当此节点运行完成后，这些变量会被赋值为API的返回内容，你可以在下游节点引用这些变量。"
          :data="outputDataDisplay"
        />
      </div>
    </div>
    <Handle type="source" :position="Position.Right" />
  </div>
</template>
